﻿using System.Collections.ObjectModel;
using System.Windows;
using FU.Capstones.IMS.Web.Common;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.DataContracts;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.EventArgs;
using FU.Capstones.IMS.Web.Silverlight.Models;
using Microsoft.Practices.Prism.Commands;
using Navigation.Silverlight;

namespace FU.Capstones.IMS.Web.Silverlight.ViewModels
{
    public class MaterialImportViewModel:ViewModelBase
   {
        public MaterialImportViewModel()
        {
            Model = new MaterialImportModel();
            
            ((MaterialImportModel)Model).GetContactCollectionCompleted += DoGetContactCollectionCompleted;
            ((MaterialImportModel)Model).GetMaterialCollectionCompleted += DoGetMaterialCollectionCompleted;
           
            ServiceCallCounter += ((MaterialImportModel)Model).GetContactCollectionAsync(false);
            NewMaterial = new Material();
            CurrentMaterial = new Material();
            CurrentSupplier = new Contact();

            CanEditOrAdd = CurrentUser.CanAddOrderMaterial || CurrentUser.CanEditOrderMaterial;
            CanAdd = CurrentUser.CanAddOrderMaterial;
        }

        //public event EventHandler<SelectionChangedEventArgs> MaterialChange;
        void DoGetMaterialCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Material> e)
        {
            if (e.Error != null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    MaterialCollection = new ObservableCollection<Material>(e.Result.Data);
                    Count = MaterialCollection.Count;
                    if (CollectionMaterial.Count > 0 && CollectionMaterial.Count <= Count)
                    {
                        MaterialCollection = SavedPage.SavedCollectionMaterial;
                    }
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        } 
        void DoGetContactCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Contact> e)
        {
            if (e.Error != null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    ContactCollection = new ObservableCollection<Contact>(e.Result.Data);

                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }
        
        #region Declare command
        //Save command use to save collection material order to database
        private DelegateCommand<object> saveCommand;
        public DelegateCommand<object> SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new DelegateCommand<object>(DoSaveCommand);
                }
                return saveCommand;
            }
        }

        //material selection change
        //Save command use to save collection material order to database
       
        private DelegateCommand<object> materialChange;
        public DelegateCommand<object> MaterialChange
        {
            get
            {
                if (materialChange == null)
                {
                    materialChange = new DelegateCommand<object>(DoMaterialChange);
                }
                return materialChange;
            }
        }

        //Back command use to turn back list order screeen
        private DelegateCommand<object> cancelCommand;
        public DelegateCommand<object> CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new DelegateCommand<object>(DoBackCommand);
                }
                return cancelCommand;
            }
        }

        //Reset command use to reset list of material
        private DelegateCommand<object> resetCommand;
        public DelegateCommand<object> ResetCommand
        {
            get
            {
                if (resetCommand == null)
                {
                    resetCommand = new DelegateCommand<object>(DoResetCommand);
                }
                return resetCommand;
            }
        }

        #endregion

        #region implement command
        private void DoMaterialChange(object obj)
        {
            if (CheckExistMaterial(NewMaterial))
            {
                ErrorMassage = "NVL này đã tồn tại, hãy chọn NVL khác hoặc thay đổi số lượng ở trang trước";
            }
        }
        private bool CheckExistMaterial(Material material)
        {
            return CollectionMaterial.Contains(material);
        }

        private void DoSaveCommand(object obj)
        {
            if (CurrentMaterial.MaterialID != 0 &&  PricePerUnit != 0 && Quantity > 0)
            {
                NewMaterial = CurrentMaterial;
                NewMaterial.PricePerUnit = PricePerUnit;
                NewMaterial.Quantity = Quantity;
                if (CurrentSupplier != null)
                {
                    if (CurrentSupplier.ContactID != 0 )
                    {
                        NewMaterial.SupplierID = CurrentSupplier.ContactID;
                    }
                }
                CollectionMaterial.Add(newMaterial);
                SavedPage.CollectionMaterial = CollectionMaterial;
                for (int i = 0; i < MaterialCollection.Count; i++)
                {
                    if (MaterialCollection[i].MaterialID == newMaterial.MaterialID)
                    {
                        MaterialCollection.RemoveAt(i);
                    }
                }
                SavedPage.SavedCollectionMaterial = MaterialCollection;

                NavigationData ndMaterial = new NavigationData();
                ndMaterial.NavigationUri = WebConstants.NavigationPages.MaterialImport;
                ndMaterial.Data = SavedPage;

                NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportMaterialOrder, ndMaterial);
            }
            else
            {
                if (CurrentMaterial.MaterialID == 0)
                {
                    ErrorMassage = "Bạn chưa chọn nguyên vật liệu";
                }
                else
                {
                    if (CurrentSupplier.ContactID == 0)
                    {
                        ErrorMassage = "Bạn chưa chọn nhà cung cấp";
                        
                    }
                    else
                    {
                        if(Quantity == 0)
                        {
                            ErrorMassage = "Bạn chưa nhập số lượng sản phẩm";
                        }
                        else
                        {
                            if (PricePerUnit == 0)
                            {
                                ErrorMassage = "Bạn chưa nhập giá của sản phẩm";
                            } 
                        }
                       
                    }
                }
            }
            
        }
        private void DoBackCommand(object obj)
        {
            NavigationData ndMaterial = new NavigationData();
            ndMaterial.NavigationUri = WebConstants.NavigationPages.MaterialImport;
            ndMaterial.Data = SavedPage;

            NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportMaterialOrder, ndMaterial);
        }
        private void DoResetCommand(object obj)
        {
             
            PricePerUnit = 0;
            Quantity = 0;

        }

        #endregion

        #region biding to combobox
        private ObservableCollection<Contact> contactCollection;
        public ObservableCollection<Contact> ContactCollection
        {
            get { return contactCollection; }
            set
            {
                if (!ReferenceEquals(contactCollection, value))
                {
                    contactCollection = value;
                    RaisePropertyChanged(() => ContactCollection);
                }
            }
        }

        private ObservableCollection<Material> materialCollection;
        public ObservableCollection<Material> MaterialCollection
        {
            get { return materialCollection; }
            set
            {
                if (!ReferenceEquals(materialCollection, value))
                {
                    materialCollection = value;
                    RaisePropertyChanged(() => MaterialCollection);
                }
            }
        }
        #endregion

       //#endregion
        private Material newMaterial;
        public Material NewMaterial
        {
            get { return newMaterial; }
            set
            {
                if (!ReferenceEquals(newMaterial, value))
                {
                    newMaterial = value;
                    RaisePropertyChanged(() => NewMaterial);
                }
            }
        }
        private Material currentMaterial;
        public Material CurrentMaterial
        {
            get { return currentMaterial; }
            set
            {
                if (!ReferenceEquals(currentMaterial, value))
                {
                    currentMaterial = value;
                    RaisePropertyChanged(() => CurrentMaterial);

                }

            }
        }
        private Contact currentSupplier;
        public Contact CurrentSupplier
        {
            get { return currentSupplier; }
            set
            {
                if (!ReferenceEquals(currentSupplier, value))
                {
                    currentSupplier = value;
                    RaisePropertyChanged(() => CurrentSupplier);

                }

            }
        }
        private string errorMassage;
        public string ErrorMassage
        {
            get { return errorMassage; }
            set
            {
                if (!ReferenceEquals(errorMassage, value))
                {
                    errorMassage = value;
                    RaisePropertyChanged(() => ErrorMassage);

                }

            }
        }
        private double pricePerUnit;
        public double PricePerUnit
        {
            get { return pricePerUnit; }
            set
            {
                pricePerUnit = value;
                RaisePropertyChanged(() =>PricePerUnit);
                
            }
        }
        private int quantity;
        public int Quantity
        {
            get { return quantity; }
            set
            {
                quantity = value;
                RaisePropertyChanged(() => Quantity);

            }
        }
        private int count;
        public int Count
        {
            get { return count; }
            set
            {
                count = value;
                RaisePropertyChanged(() => Count);

            }
        }
        #region CollectionMaterial
        private ObservableCollection<Material> collectionMaterial;
        public ObservableCollection<Material> CollectionMaterial
        {
            get { return collectionMaterial; }
            set
            {
                if (!ReferenceEquals(collectionMaterial, value))
                {
                    collectionMaterial = value;
                    RaisePropertyChanged(() => CollectionMaterial);
                }
            }
        }
        private ExportMaterialOrderViewModel savedPage;
        public ExportMaterialOrderViewModel SavedPage
        {
            get { return savedPage; }
            set
            {
                if (!ReferenceEquals(savedPage, value))
                {
                    savedPage = value;
                    RaisePropertyChanged(() => SavedPage);
                }
            }
        }
        #endregion

        #region Implementation of INavigationAware

        public override void OnNavigate(object extraData)
        {
             
            var nd = (NavigationData)extraData;
            if (nd != null)
            {
                if (nd.NavigationUri.Equals(WebConstants.NavigationPages.ExportMaterialOrder))
                {
                    if (nd.Data != null)
                    {
                        if (nd.Data.GetType().Equals(typeof(ExportMaterialOrderViewModel)))
                        {
                            SavedPage = (ExportMaterialOrderViewModel) nd.Data;
                            CollectionMaterial = SavedPage.CollectionMaterial;
                            ServiceCallCounter += ((MaterialImportModel)Model).GetMaterialCollectionAsync(false);
                           
                        }
                    }

                }
            }
            else
            {
                 
                CollectionMaterial = new ObservableCollection<Material>();
                SavedPage = new ExportMaterialOrderViewModel();
            }
            
        }

        public override void OnLeave()
        {
            //will be implemented in the sub classes
        }

        #endregion

    }
    
}
